package org.xawl.news.servlet.base;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xawl.news.util.StringUtil;

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 视图页面后缀
	private static final String PAGE_SUFFIX = ".jsp";
	// 试图页面目录
	private static final String PAGE_PREFIX = "/WEB-INF/jsp/";

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取 methodName 参数，它是用户想调用的方法名称
		String methodName = request.getParameter("method");
		if(StringUtil.isEmpty(methodName)) {
			response.sendRedirect("login.jsp");
		}
        Method method = null;
        //2.通过方法名称获取 Method 对象
        try {
        	//[3]使其子类能够调用自身的私有方法
			method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			//3.通过 Method 对象来调用它
			method.setAccessible(true);
			String url = (String) method.invoke(this, request, response);
			 //[2]简化转发和重定向功能
            /*考虑到用 f、r 分别代替 forward、redirect 对他人阅读代码可能会造成阅读障碍故，在此并未进行替代*/
			if (url != null && url.trim().length() > 0) {
				if(url.indexOf(":") == -1) {
					request.getRequestDispatcher(url).forward(request, response);
					return;
				}
				String prefix = url.split(":")[0];
				String suffix = url.split(":")[1];
			    //子类中的转发格式 forward:/index.jsp
			    if (prefix.equals("forward")) {
			    	request.getRequestDispatcher(PAGE_PREFIX + suffix + PAGE_SUFFIX).forward(request, response);
			        //子类中的重定向格式 redirect:/index.jsp
			    } else if (prefix.equals("redirect")) {
			    	if(request.getContextPath().endsWith("/")) {
			    		response.sendRedirect(request.getContextPath() + suffix);
			    	}
			    	response.sendRedirect(request.getContextPath()+ "/" + suffix);
			    } else {
			    	request.getRequestDispatcher(url).forward(request, response);
			    }
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	
}
